package notify

import (
	"fmt"
	"github.com/didi/nightingale/src/common/address"
	"github.com/didi/nightingale/src/common/dataobj"
	"github.com/toolkits/pkg/logger"
	"github.com/toolkits/pkg/net/httplib"
	"math/rand"
	"strings"
	"time"
)

func Send(tos []string, content, subject string, notifyType string) error {
	addrs := address.GetHTTPAddresses("rdb")
	perm := rand.Perm(len(addrs))

	var err error
	for i := range perm {
		data := dataobj.Notify{
			Tos:     tos,
			Subject: subject,
			Content: content,
		}

		url := fmt.Sprintf("%s/v1/rdb/sender/%s", addrs[perm[i]], notifyType)
		if !(strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")) {
			url = "http://" + url
		}

		res, code, err := httplib.PostJSON(url, time.Second*5, data, map[string]string{"X-Srv-Token": "rdb-builtin-token"})
		if err != nil {
			logger.Errorf("call sender api failed, server: %v, data: %+v, err: %v, resp:%v, status code:%d", url, data, err, string(res), code)
			continue
		}

		if code != 200 {
			logger.Errorf("call sender api failed, server: %v, data: %+v, resp:%v, code:%d", url, data, string(res), code)
			continue
		}

		if err == nil {
			logger.Infof("curl %s response: %s", url, string(res))
			break
		}

	}

	return err
}
